import { Button, Cascader, Modal, message } from 'antd';
import {
  FormPanel,
  FormPanelType,
  InputType,
  Utils,
  type FormPanelObject,
  FormPanelBtnAlign,
  FormPanelBtnDisplay,
  MinioUploadListType,
} from 'lfun-bg-comp';
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { SCHOOL_OPERATION_TYPE, SCHOOL_ORG_TYPE } from '@/constant/schoolOptions';
import { buildPageItemTxtByEduType, getPathRoot } from '@/utils';
import { CreatePlanningSchool, createPlanningSchool } from '@/service/unit/planning';
import {
  getEduLevelOptions,
  getPlanningSchoolCategoryOptions,
  getPlanningSchoolOperationTypeOptions,
} from '@/service/options';
import useCountry from '@/hooks/useCountry';
import SelectList from './component/select-list';
import SelectList2 from './component/select-list2';

// eslint-disable-next-line react/require-default-props
const Groups: React.FC<{ show: boolean; onCancel: any; onOk: any; editType?: string; values?: any }> = ({
  show,
  onCancel,
  onOk,
  editType,
  values,
}) => {
  const navigate = useNavigate();
  const country = useCountry();
  const [form, setForm] = useState() as any;
  const [showExplainModel, setShowExplainModel] = React.useState(false);
  const [postData, setPostData] = useState({});

  const createTemplate: FormPanelType[] = [
    {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      span: 24,
      inputs: [
        {
          label: buildPageItemTxtByEduType('园所名称(规划口径)'),
          name: 'planning_school_name',
          key: 'planning_school_name',
          required: true,
          textRange: [0, 20],
        },
        // {
        //   label: buildPageItemTxtByEduType('园所代码'),
        //   name: 'planning_school_no',
        //   key: 'planning_school_no',
        //   required: true,
        //   textRange: [0, 20],
        // },
        // {
        //   label: '地域管辖区',
        //   name: 'block',
        //   key: 'block',
        //   required: true,
        //   inputType: InputType.select,
        //   renderOption: country,
        // },
        // {
        //   label: '行政管辖区',
        //   name: 'borough',
        //   key: 'borough',
        //   required: true,
        //   inputType: InputType.select,
        //   renderOption: country,
        // },
        {
          label: '行政归属地',
          name: 'borough',
          key: 'borough',
          inputType: InputType.children,
          children: <SelectList />,
          renderValidate: form => {
            const value = form.getFieldsValue()?.borough || {};
            if (value.key1 && value.key2 && value.key3) {
              return false;
            }
            return '行政归属地必填!';
          },

          required: true,
          // span: 20,
          props: {
            labelCol: { span: 4 },
            // wrapperCol: { span: 17 },
          },
        },

        {
          label: '所在地址',
          name: 'a0',
          key: 'a0',
          inputType: InputType.children,
          children: <SelectList2 />,
          renderValidate: form => {
            const value = form.getFieldsValue()?.a0 || {};
            if (value.key1 && value.key2 && value.key3 && value.key4 && value.key5) {
              return false;
            }
            return '行政归属地必填!';
          },
          required: true,
          props: {
            labelCol: { span: 4 },
            // wrapperCol: { span: 17 },
          },
        },
        {
          label: '详细地址',
          name: 'a1',
          key: 'a1',
          inputType: InputType.textarea,
          required: true,
        },
        // {
        //   label: '教育层次',
        //   name: 'planning_school_edu_level',
        //   key: 'planning_school_edu_level',
        //   relationFields: ['planning_school_category', 'planning_school_operation_type'],
        //   required: true,
        //   inputType: InputType.select,
        //   //renderOption: SCHOOL_OPERATION_TYPE,
        //   renderOption: () => getEduLevelOptions(),
        // },
        {
          label: '学校性质',
          name: 'planning_school_edu_level',
          key: 'planning_school_edu_level',
          relationFields: ['planning_school_category', 'planning_school_operation_type'],
          inputType: InputType.select,
          renderOption: SCHOOL_OPERATION_TYPE,
          required: true,
        },
        {
          label: '办学类型分组',
          name: 'planning_school_category',
          key: 'planning_school_category',
          required: true,
          relationFields: ['planning_school_operation_type'],
          inputType: InputType.select,
          renderOption: async (form: FormPanelObject) => {
            return getPlanningSchoolCategoryOptions(form, 'planning_school_edu_level');
          },
        },
        {
          label: '办学类型',
          name: 'planning_school_operation_type',
          key: 'planning_school_operation_type',
          required: true,
          inputType: InputType.select,
          renderOption: async (form: FormPanelObject) =>
            getPlanningSchoolOperationTypeOptions(form, 'planning_school_edu_level', 'planning_school_category'),
        },
        {
          label: '办别',
          name: 'planning_school_org_type',
          key: 'planning_school_org_type',
          required: true,
          inputType: InputType.select,
          renderOption: SCHOOL_ORG_TYPE,
        },
        // {
        //   label: '学校星级',
        //   name: 'planning_school_level',
        //   key: 'planning_school_level',
        //   required: true,
        //   inputType: InputType.select,
        //   renderOption: KG_LEVEL,
        // },
      ],
    },
  ];
  const template2 = [
    {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      span: 24,
      inputs: [
        {
          label: '变更原因',
          name: 'bb',
          key: 'bb',
          required: true,
          textRange: [0, 200],
        },
        {
          label: '相关证件上传',
          name: 'aa',
          key: 'aa',

          inputType: InputType.minioUpload,
          inputProps: {
            listType: MinioUploadListType.picture,
            supportFileTypes: [
              'image/jpg',
              'image/jpeg',
              'application/rar',
              'application/x-compressed',
              'application/zip',
              'application/x-zip-compressed',
              'application/doc',
              'application/msword',
              'application/docx',
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
              'application/pdf',
            ],
            placeholder: '支持扩展文名：.rar .zip .doc .docx .pdf .jpg',
            maxCount: 1,
            text: '上传文件',
            uploadSrv: '/school/v1/storage/school-upload-uri',
          },
        },
      ],
    },
  ];
  const getCreateDefParams = () => {
    let params: CreatePlanningSchool = {};
    if (Utils.getProps('edu_type') === 'kg') {
      params = {
        planning_school_edu_level: 'preSchoolEducation',
        planning_school_category: 'kindergarten',
      };
    }
    if (Utils.getProps('edu_type') === 'vocational') {
      params = {
        planning_school_edu_level: 'secondaryEducation',
        planning_school_category: 'secondaryVocationalSchool',
      };
    }
    // = {
    //   planning_school_edu_level: Utils.getProps('edu_type'),
    // };
    return { params, ...values };
  };

  const onSubmit = async (formPanelObject, callback?: any) => {
    const values = formPanelObject.getFieldsValue();
    const planning: CreatePlanningSchool = { ...values, borough: values.borough };
    if (editType !== 'edit') {
      await _postCreate(formPanelObject, planning, callback);
    } else {
      setPostData(planning);
      setShowExplainModel(true);
    }

    return true;
  };
  const onSubmit2 = async () => {
    onSubmit(form, res => {
      navigate(`${getPathRoot()}/planning/edit/${res.data.id}`, { state: { ...res.data } });
    });
  };
  const _postCreate = async (formPanelObject, planning, callback?: any) => {
    const res = await createPlanningSchool(planning);
    if (res.success) {
      message.success(buildPageItemTxtByEduType('新增园所名称(规划口径)成功'));
      onCancel(formPanelObject);
      formPanelObject.resetFields();
      // eslint-disable-next-line no-unused-expressions
      callback && callback(res);
    } else {
      formPanelObject.reVaildation(res);
    }
  };

  const _postEdit = async (formPanelObject, planning, values) => {
    const res = await createPlanningSchool(planning);
    if (res.success) {
      message.success(buildPageItemTxtByEduType('修改园所名称(规划口径)成功'));
      onCancel(formPanelObject);
      formPanelObject.resetFields();
    } else {
      formPanelObject.reVaildation(res);
    }
  };
  const buildBtns = () => {
    return [
      editType !== 'edit' && (
        <Button type="primary" onClick={() => onSubmit2()}>
          提交并继续
        </Button>
      ),
    ];
  };
  const titleCompute = () => {
    if (editType !== 'edit') {
      return buildPageItemTxtByEduType('新增园所(规划口径)');
    }
    if (showExplainModel) {
      return '关键信息变更说明';
    }
    return '关键信息变更';
  };

  return (
    <>
      <Modal
        className="close_reson"
        open={show}
        title={titleCompute()}
        footer={[]}
        cancelText="返回"
        okText="确认"
        onCancel={onCancel}
        width="1000px"
      >
        {!showExplainModel && (
          <FormPanel
            btnsAlign={FormPanelBtnAlign.center}
            buttonsDisplay={FormPanelBtnDisplay.block}
            restBtnText="返回"
            submitBtnText={editType !== 'edit' ? '确定' : '下一步'}
            values={getCreateDefParams()} // todo: 这里后续从token获取
            template={createTemplate}
            buttons={buildBtns()}
            onLoad={form => {
              setForm(form);
            }}
            onFinish={async (formPanelObject: FormPanelObject) => {
              onSubmit(formPanelObject);
            }}
            onReset={form => {
              if (typeof onCancel === 'function') {
                form.resetFields();
                onCancel(form);
              }
              return true;
            }}
          />
        )}
        {showExplainModel && (
          <FormPanel
            template={template2}
            key={1}
            btnsAlign={FormPanelBtnAlign.center}
            buttonsDisplay={FormPanelBtnDisplay.block}
            restBtnText="返回"
            submitBtnText="确定"
            onFinish={async (formPanelObject: FormPanelObject) => {
              const values = formPanelObject.getFieldsValue();
              await _postEdit(formPanelObject, postData, values);
            }}
            onReset={() => onCancel(form)}
          />
        )}
      </Modal>
    </>
  );
};

export default Groups;
